package org.zoomdev.zoom.event.modules;

import org.zoomdev.zoom.event.EventListener;
import org.zoomdev.zoom.event.EventService;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

class EventServiceImpl implements EventService {

    private final Map<String, CopyOnWriteArrayList<EventListener>> map = new ConcurrentHashMap<>();

    @Override
    public void addListener(String name, EventListener listener) {
        CopyOnWriteArrayList<EventListener> list = map.computeIfAbsent(name, (name1) -> new CopyOnWriteArrayList<>());
        if (!list.contains(listener)) {
            list.add(listener);
        }
    }

    @Override
    public void removeListener(String name, EventListener listener) {
        CopyOnWriteArrayList<EventListener> list = map.get(name);
        if (list != null && list.remove(listener)) {
            // 清理空列表
            if (list.isEmpty()) {
                map.remove(name, list);
            }
        }
    }


    @Override
    public void notifyObservers(String name, Object data) {
        CopyOnWriteArrayList<EventListener> list = map.get(name);
        if (list == null) {
            return;
        }
        for (EventListener listener : list) {
            listener.onEvent(data);
        }
    }
}
